//
//  SoftUpdateRootViewController.m
//  CPICMobileServiceApp
//
//  Created by sinosoft on 13-2-28.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "SoftUpdateRootViewController.h"
#import "Config.h"
#import "RCAlertViewUtil.h"
#import "ASIHTTPRequest.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"
#import "RCAlertViewUtil.h"
#import "UIImageView+WebCache.h"
#import "NSString+Regex.h"
#import "RCSystemService.h"

@interface SoftUpdateRootViewController ()

@end

@implementation SoftUpdateRootViewController
@synthesize progress;
@synthesize UpdateURL;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title=@"软件更新";
        //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"软件更新");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"软件更新");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"软件更新");
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }
    
    UIImageView *imgReflection=[[UIImageView alloc]initWithFrame:CGRectMake(35, 100, 260, 290)];
    imgReflection.image=[UIImage imageNamed:@"SoftUpdate_Reflection"];
    [self.view addSubview:imgReflection];
    
    UIButton *btnVersion=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btnVersion setImage:[UIImage imageNamed:@"SoftUpdate_01"] forState:UIControlStateNormal];
    //[btnVersion setTitle:@"当前版本" forState:UIControlStateNormal];
    btnVersion.frame=CGRectMake(35, 101, 218/2, 218/2);
    [btnVersion addTarget:self action:@selector(getVersion) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnVersion];
    
    UIButton *btnUpdate=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btnUpdate setImage:[UIImage imageNamed:@"SoftUpdate_02"] forState:UIControlStateNormal];
    //[btnUpdate setTitle:@"版本更新" forState:UIControlStateNormal];
    btnUpdate.frame=CGRectMake(175, 101, 218/2, 218/2);
    [btnUpdate addTarget:self action:@selector(updateVersion) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnUpdate];
    
    UIButton *btnAbout=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btnAbout setImage:[UIImage imageNamed:@"SoftUpdate_04"] forState:UIControlStateNormal];
    //[btnAbout setTitle:@"版本介绍" forState:UIControlStateNormal];
    btnAbout.frame=CGRectMake(35, 238, 218/2, 218/2);
    [btnAbout addTarget:self action:@selector(aboutVersion) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAbout];
    
    UIButton *btnSupport=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btnSupport setImage:[UIImage imageNamed:@"SoftUpdate_03"] forState:UIControlStateNormal];
    //[btnSupport setTitle:@"支持我们" forState:UIControlStateNormal];
    btnSupport.frame=CGRectMake(175, 238, 218/2, 218/2);
    [btnSupport addTarget:self action:@selector(SupportUs) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSupport];
}

-(void) ClickCallOutBtn
{
    
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setRequest//向太保移动平台发送请求报文
{
//    NSString *strRequestCode=@"RequestCode=60801";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    [dicRequest setObject:@"admin22" forKey:@"userAccount"];
    [dicRequest setObject:[RCSystemService currentVersion] forKey:@"version"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"60801" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        //[NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    };
    
    
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    serverceVersion=[[NSString alloc]initWithFormat:@"%@",[dictResponse objectForKey:@"version"]];
    strUpdateURL=[[NSString alloc]initWithFormat:@"%@",[dictResponse objectForKey:@"appUrl"]];
    strUpdateURL=[strUpdateURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"服务器版本是%@",serverceVersion);
    NSLog(@"更新地址是%@",strUpdateURL);
    BOOL isOldVersion = NO;
    isOldVersion = [RCSystemService isOldVersionCompareWithVersionFromServer:serverceVersion];
    NSString *strUpdateContent=[[NSString alloc]initWithFormat:@"有新版本,是否需要更新,更新内容:%@",[dictResponse objectForKey:@"versionContent"]];
    if (isOldVersion) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息"
                                                       message:strUpdateContent
                                                      delegate:self
                                             cancelButtonTitle:@"以后再说"
                                             otherButtonTitles:@"现在更新",nil];
        [alert setTag:1];
        [alert show];
    }
    else
    {
        [self justShowMessage:@"当前已是最新版本!" title:@"提示"];
    }
}

#pragma mark--
#pragma mark-- UIAlertViewDelegate
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==1) {
        if (buttonIndex==0) {
            
        }
        else
        {
            if (strUpdateURL.length==0) {
                [self justShowMessage:@"更新地址为空" title:@"注意"];
            }
            else
            {
                UpdateURL=[NSURL URLWithString:strUpdateURL];
                [[UIApplication sharedApplication]openURL:UpdateURL];
            }
        }
    }
}
-(void)downLoadVersion
{
    
}
- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}



-(void)getVersion
{
    //[self justShowMessage:@"当前版本号V0.0.1" title:@""];
    NSString *strVersion=[[NSString alloc]initWithFormat:@"当前版本号是%@",[RCSystemService currentVersion]];
    [self justShowMessage:strVersion title:nil];
}

-(void)updateVersion
{
    //[self justShowMessage:@"当前版本已是最新" title:@""];
    [self setRequest];
}

-(void)aboutVersion
{
    [self justShowMessage:@"车E服，依托太平洋产险强大的品牌影响力，联合本地优秀车辆服务供应商，为私家车主提供各类优惠服务。车- 人- 美好生活，尽在车E服" title:@""];
}

-(void)SupportUs
{
    [self justShowMessage:@"请继续支持车E服!" title:@""];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc
{
    //[UpdateURL release];
    [super dealloc];
}

@end
